//
//  ContentView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    
    @State private var selectedTab: Tab = .home
    @State var showAddAccountingView:Bool = false
    // 定义一个状态变量，当值改变时，HomeView会通过 onChange 监听到，从而刷新数据
    @State private var homeReloadTrigger = false
    @State private var showPrivacyArgee = false
    @State private var selectedDetail: AccountingDetailCombine? = nil
    
    init () {
        //Use this if NavigationBarTitle is with Large Font
        UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor(Color.koiColorTitle)]
        //Use this if NavigationBarTitle is with displayMode = .inline
        UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor(Color.koiColorTitle)]
    }
    
    var body: some View {
        ZStack {
            if (appState.isLoggedIn) {
                NavigationStack {
                    ZStack(alignment: .bottom) {
                        Group {
                            switch selectedTab {
                            case .home:
                                // TODO init 代码从 HomeView 中移出来
                                HomeView(reloadTrigger: $homeReloadTrigger)
                            case .chart:
                                ChartView()
                            }
                        }.frame(maxWidth: .infinity, maxHeight: .infinity)
                        bottomBar
                    }
                    .background(Color.white)
                    .ignoresSafeArea(edges:.bottom)
                }
                .onDisappear{
                    KoiEvent.toLogin.removeObserver(self)
                }
                .onAppear {
                    NotificationCenter.default.addObserver(forName: .tokenInvalid, object: nil, queue: .main) { notification in
                        if notification.name == .tokenInvalid {
                            appState.isLoggedIn = false
                        }
                    }
                    KoiSync.standard.syncFull()
                    KoiEvent.toLogin.addObserver{ notification in
                        if notification.name == .toLogin {
                            appState.isLoggedIn = false
                        }
                    }
                }
            } else {
                LoginView()
            }
        }.fullScreenCover(
            isPresented: $showPrivacyArgee,
            onDismiss: {
                if !showPrivacyArgee {
                    // 测试网络连接
                    KoiAccountingNetApi.standard.testNet { _ in
                        logger.info("test net")
                    }
                }
            },
            content: {
                PrivacyGuideView(
                    argeeClick: {
                        PrivacyGuide.standard.setAgree(agree: true)
                            showPrivacyArgee = false
                    },
                    exitClick: {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                            exit(0)
                        }
                    }
                )
            }
        )
        .onAppear{
            showPrivacyArgee = !PrivacyGuide.standard.isAgree()
        }
        
    }
    
    var bottomBar: some View {
        HStack(alignment: .center, spacing: 0) {
            Spacer()
            Button(action:{
                selectedTab = .home
            }) {
                Image("koi_ic_tab_home")
                    .renderingMode(.template)
                    .foregroundColor(selectedTab == Tab.home ? Color.koiColorTitle : Color.koiColorTitleSecond)
                    .padding(5)
            }
            Button(action:{
                showAddAccountingView = true
            }) {
                Image("koi_ic_tab_add").padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
            }.sheet(isPresented: $showAddAccountingView, onDismiss:{
                homeReloadTrigger.toggle()
            }){
                AddAccountingView().presentationDetents([.large])
            }
            Button(action:{
                selectedTab = .chart
            }) {
                Image("koi_ic_tab_chart")
                    .renderingMode(.template)
                    .foregroundColor(selectedTab == Tab.chart ? Color.koiColorTitle : Color.koiColorTitleSecond)
                    .padding(5)
            }
            Spacer()
        }
        .frame(height: 70, alignment: .center)
        .background(Color.white.blur(radius: 40, opaque: true))
        .cornerRadius(40)
        .overlay(
            RoundedRectangle(cornerRadius: 40)
                .stroke(Color.koiColorDivider, lineWidth: 0.5)
        )
        .shadow(color:Color.koiColorBottomShadow, radius: 5,x:0,y: 10)
        .padding(EdgeInsets(top: 20, leading: 65, bottom: 34, trailing: 65))
    }
}

enum Tab: String {
    case home
    case chart
}

#Preview {
    ContentView()
}
